﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.DynamicData;
using Telerik.Web.UI;

namespace FlexiCommerce.Web.Admin.FlexiAdmin.DynamicData.FieldTemplates
{
    public partial class Categories_Edit : FieldTemplateUserControl
    {
        private IList<Components.Category> categories;
        protected override void OnInit(EventArgs e)
        {

            base.OnInit(e);
            MetaTable table = MetaModel.Default.GetTable(typeof(Components.Category));
            DomainDataSourceCategories.SetTable(table);
        }
        public override void DataBind()
        {
            if (Host.Mode == DataBoundControlMode.Edit)
            {
                categories = FieldValue as IList<Components.Category>;
            }
            base.DataBind();
        }
        protected override void ExtractValues(System.Collections.Specialized.IOrderedDictionary dictionary)
        {

            IList<Components.Category> newcategories = new List<Components.Category>();
            foreach (RadTreeNode node in RadTreeViewCategories.CheckedNodes)
            {
                Components.Category category = FlexiCommerce.Context.Persister.Get<Components.Category>(int.Parse(node.Value));
                if (category != null)
                    newcategories.Add(category);
            }
            dictionary[Column.Name] = newcategories;
        }
        protected void RadTreeViewCategories_DataBound(object sender, EventArgs e)
        {
            if (this.Host.Mode == DataBoundControlMode.Edit)
            {
                foreach (Components.Category c in categories)
                {
                    RadTreeNode node = RadTreeViewCategories.FindNodeByValue(c.ID.ToString());
                    if (node != null)
                    {
                        node.Checked = true;
                        node.ExpandParentNodes();
                    }
                }
            }
        }
    }
}